<template>
  <div class="schedule-container">
    <!-- AI智能助手区域 -->
    <el-card class="ai-assistant-card">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-s-help"></i> AI智能助手</span>
        <div style="float: right">
          <!-- 新增：模型选择下拉框 -->
          <el-select
            v-model="selectedModel"
            size="mini"
            style="width: 140px; margin-right: 10px"
          >
            <el-option label="硅基流动AI" value="liudong"></el-option>
            <el-option label="ollma" value="ollma"></el-option>
          </el-select>
          <!-- <el-tag 
            :type="aiServiceStatus.type" 
            size="mini" 
            style="margin-right: 10px; cursor: pointer;"
            :title="aiServiceStatus.message"
          >
            <i :class="aiServiceStatus.icon"></i> {{ aiServiceStatus.text }}
          </el-tag> -->
          <el-button
            v-if="aiMessages.length > 0"
            style="margin-right: 10px; padding: 3px 0"
            type="text"
            @click="clearAiChat"
            title="清除聊天记录"
          >
            <i class="el-icon-delete"></i> 清除
          </el-button>
          <el-button
            style="padding: 3px 0"
            type="text"
            @click="toggleAiAssistant"
          >
            {{ showAiAssistant ? "收起" : "展开" }}
          </el-button>
        </div>
      </div>
      <div v-if="showAiAssistant" class="ai-assistant-content">
        <div class="ai-input-area">
          <el-input
            v-model="aiInputMessage"
            placeholder="告诉AI您的需求，比如：'帮我安排明天的会议'、'优化我的日程安排'、'提醒我重要事项'"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            @keyup.enter.native="sendAiMessage"
            @keydown.ctrl.delete.native="clearAiChat"
            :disabled="aiLoading"
          ></el-input>
          <div class="ai-input-tips">
            <el-button
              type="text"
              size="mini"
              @click="showAiExamples"
              style="margin-left: 10px; color: #409eff"
            >
              <i class="el-icon-question"></i> 查看示例
            </el-button>
          </div>
          <el-button
            type="primary"
            :class="['ai-send-btn', { 'loading-btn': aiLoading }]"
            @click="sendAiMessage"
            :disabled="aiLoading"
          >
            <i v-if="!aiLoading" class="el-icon-s-promotion"></i>
            <span v-else class="loading-dots">
              <span class="dot">.</span><span class="dot">.</span
              ><span class="dot">.</span>
            </span>
          </el-button>
        </div>

        <!-- AI回复区域 -->
        <div v-if="aiMessages.length > 0" class="ai-messages">
          <div class="ai-messages-header">
            <span>聊天记录 ({{ aiMessages.length }})</span>
            <el-button
              type="text"
              size="mini"
              @click="clearAiChat"
              title="清除聊天记录"
            >
              <i class="el-icon-delete"></i> 清除
            </el-button>
          </div>
          <div
            class="ai-messages-content"
            ref="aiMessagesContent"
            @scroll="checkScrollPosition"
          >
            <div
              v-for="(message, index) in aiMessages"
              :key="index"
              :class="['ai-message', message.role, {
                'thinking': message.isThinking,
                'error': message.isError
              }]"
            >
              <div class="ai-avatar">
                <img
                  v-if="message.role === 'assistant'"
                  src="@/assets/ai-avatar.png"
                  alt="AI"
                />
                <div v-else class="user-avatar">
                  <i class="el-icon-user-solid"></i>
                </div>
              </div>
              <div class="ai-message-content">
                <pre v-if="!message.isThinking">{{ message.content }}</pre>
                <div v-else class="thinking-content">
                  <span class="thinking-text">{{ message.content }}</span>
                  <span class="thinking-dots">
                    <span class="dot">.</span><span class="dot">.</span><span class="dot">.</span>
                  </span>
                </div>

                <!-- AI建议按钮 -->
                <div
                  v-if="
                    message.role === 'assistant' &&
                    index === aiMessages.length - 1 &&
                    aiSuggestions.length > 0 &&
                    !message.isThinking &&
                    !message.isError
                  "
                  class="ai-suggestions"
                >
                  <h4>AI建议：</h4>
                  <div class="suggestion-list">
                    <el-tag
                      v-for="(suggestion, suggestionIndex) in aiSuggestions"
                      :key="suggestionIndex"
                      :type="suggestion.type"
                      class="suggestion-tag"
                      @click="applySuggestion(suggestion)"
                    >
                      {{ suggestion.text }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 滚动到底部按钮 -->
          <el-button
            v-if="showScrollToBottom"
            class="scroll-to-bottom-btn"
            icon="el-icon-bottom"
            circle
            size="mini"
            @click="scrollToBottom"
            title="滚动到底部"
          />
        </div>

        <!-- 空状态提示 -->
        <div v-else class="ai-empty-state">
          <div class="empty-icon">
            <i class="el-icon-chat-dot-round"></i>
          </div>
          <div class="empty-text">
            <h4>开始与AI助手对话</h4>
            <p>我可以帮您安排日程、优化时间、设置提醒等</p>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 倒计时提醒区域 -->
    <el-card class="countdown-card" v-if="upcomingSchedules.length > 0">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-time"></i> 即将到来的日程</span>
        <div style="float: right">
          <!-- 删除实时更新相关的el-select和el-tag，仅保留手动刷新按钮、更新时间和页面隐藏标签 -->
          <el-button
            size="mini"
            type="text"
            @click="manualRefresh"
            :loading="refreshing"
            style="margin-right: 10px; color: white"
            title="手动刷新"
          >
            <i class="el-icon-refresh"></i>
          </el-button>
          <span class="update-time"
            >最后更新: {{ formatUpdateTime(lastUpdateTime) }}</span
          >
          <el-tag
            v-if="!isPageVisible"
            size="mini"
            type="info"
            style="margin-left: 10px"
          >
            <i class="el-icon-view"></i> 页面隐藏中
          </el-tag>
        </div>
      </div>
      <div class="countdown-list">
        <div
          v-for="schedule in upcomingSchedules"
          :key="schedule.id"
          class="countdown-item"
          :class="{
            urgent: schedule.isUrgent,
            'starting-soon': schedule.isStartingSoon,
            'ending-soon': schedule.isEndingSoon,
          }"
        >
          <div class="countdown-info">
            <div class="schedule-title">{{ schedule.title }}</div>
            <div class="countdown-time">
              <span class="time-label">开始时间：</span>
              <span class="time-value">{{
                parseTime(schedule.startTime)
              }}</span>
            </div>
            <div class="countdown-remaining">
              <span class="remaining-label">距离开始：</span>
              <span
                class="remaining-value"
                :class="{
                  'urgent-text': schedule.isUrgent,
                  'starting-soon-text': schedule.isStartingSoon,
                  'ending-soon-text': schedule.isEndingSoon,
                }"
              >
                {{ schedule.countdownText }}
              </span>
            </div>
            <div v-if="schedule.isUrgent" class="schedule-status">
              <el-tag type="warning" size="mini">
                <i class="el-icon-time"></i> 进行中
              </el-tag>
            </div>
            <div v-else-if="schedule.isStartingSoon" class="schedule-status">
              <el-tag type="danger" size="mini">
                <i class="el-icon-bell"></i> 即将开始
              </el-tag>
            </div>
            <div v-else-if="schedule.isEndingSoon" class="schedule-status">
              <el-tag type="info" size="mini">
                <i class="el-icon-warning"></i> 即将结束
              </el-tag>
            </div>
          </div>
          <div class="countdown-actions">
            <el-button size="mini" type="primary" @click="showDetail(schedule)"
              >查看</el-button
            >
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="calendar-card">
      <div slot="header" class="clearfix">
        <span>日程管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="showAddDialog"
        >
          添加日程
        </el-button>
      </div>
      <el-calendar v-model="currentDate" @select="handleDateSelect">
        <template #dateCell="{ date, data }">
          <div class="calendar-day">
            <div class="day-number">
              {{ data.day.split("-").slice(2).join("-") }}
            </div>
            <div class="schedules">
              <div
                v-for="(item, index) in getSchedulesByDate(date)"
                :key="index"
                class="schedule-item"
                :style="{
                  backgroundColor: item.color || '#409EFF',
                  color: '#ffffff',
                }"
                @click="showDetail(item)"
              >
                {{ item.title }}
              </div>
            </div>
          </div>
        </template>
      </el-calendar>
    </el-card>

    <!-- 日程列表视图 -->
    <el-card class="schedule-list-card">
      <div slot="header" class="clearfix">
        <span>日程列表</span>
        <div style="float: right">
          <el-radio-group v-model="listViewType" size="small">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div
        class="time-range-info"
        style="
          margin-bottom: 10px;
          padding: 8px 12px;
          background: #f5f7fa;
          border-radius: 4px;
          font-size: 12px;
          color: #606266;
        "
      >
        <span v-if="listViewType === 'all'">
          显示全部日程 (共 {{ schedules.length }} 个)
        </span>
        <span v-else-if="listViewType === 'week'">
          显示时间范围：{{ formatDateRange(getWeekStart(), getWeekEnd()) }}
        </span>
        <span v-else>
          显示时间范围：{{ formatDateRange(getMonthStart(), getMonthEnd()) }}
        </span>
      </div>
      <el-table :data="filteredSchedules" style="width: 100%">
        <el-table-column prop="title" label="日程标题" min-width="120">
          <template slot-scope="scope">
            <el-tag :color="scope.row.color" effect="dark">{{
              scope.row.title
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template slot-scope="scope">
            {{ parseTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template slot-scope="scope">
            {{ parseTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remind" label="提醒" width="100">
          <template slot-scope="scope">
            <el-tag size="mini" type="info">{{
              getRemindLabel(scope.row.remind)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getScheduleStatus(scope.row).type" size="mini">
              {{ getScheduleStatus(scope.row).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="showDetail(scope.row)"
              >查看</el-button
            >
            <el-button size="mini" type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑日程对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="true"
      :append-to-body="true"
    >
      <el-form
        :model="scheduleForm"
        label-width="80px"
        :rules="scheduleFormRules"
        ref="scheduleForm"
      >
        <el-form-item label="日程标题" prop="title">
          <el-input v-model="scheduleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="scheduleForm.startTime"
            type="datetime"
            placeholder="选择日期时间"
            @change="onStartTimeChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="scheduleForm.endTime"
            type="datetime"
            placeholder="选择日期时间"
            :picker-options="endTimePickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="提醒">
          <el-select v-model="scheduleForm.remind" placeholder="请选择">
            <el-option
              v-for="item in remindOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="scheduleForm.color"></el-color-picker>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            :rows="2"
            v-model="scheduleForm.description"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="danger" v-if="isEdit" @click="handleDeleteFromDialog"
          >删 除</el-button
        >
        <el-button type="primary" @click="saveSchedule">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 智能提醒设置对话框 -->
    <el-dialog
      title="智能提醒设置"
      :visible.sync="reminderDialogVisible"
      width="40%"
      :close-on-click-modal="true"
      :append-to-body="true"
    >
      <div class="reminder-settings">
        <el-form :model="reminderSettings" label-width="120px">
          <el-form-item label="启用浏览器通知">
            <el-switch
              v-model="reminderSettings.browserNotification"
            ></el-switch>
            <div class="form-tip">允许浏览器发送桌面通知</div>
          </el-form-item>

          <el-form-item label="启用声音提醒">
            <el-switch v-model="reminderSettings.soundNotification"></el-switch>
            <div class="form-tip">播放提示音</div>
          </el-form-item>

          <el-form-item label="默认提醒时间">
            <el-select
              v-model="reminderSettings.defaultRemindTime"
              placeholder="请选择"
            >
              <el-option label="提前5分钟" value="5min"></el-option>
              <el-option label="提前15分钟" value="15min"></el-option>
              <el-option label="提前30分钟" value="30min"></el-option>
              <el-option label="提前1小时" value="1hour"></el-option>
              <el-option label="提前1天" value="1day"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="智能提醒规则">
            <el-checkbox-group v-model="reminderSettings.smartRules">
              <el-checkbox label="conflict">时间冲突提醒</el-checkbox>
              <el-checkbox label="overlap">日程重叠提醒</el-checkbox>
              <el-checkbox label="duration">时长异常提醒</el-checkbox>
              <el-checkbox label="gap">空闲时间建议</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="提醒消息模板">
            <el-input
              type="textarea"
              :rows="3"
              v-model="reminderSettings.messageTemplate"
              placeholder="例如：{title} 将在 {time} 开始，请做好准备！"
            ></el-input>
            <div class="form-tip">
              可用变量：{title} - 日程标题，{time} - 开始时间，{duration} -
              持续时间
            </div>
          </el-form-item>
        </el-form>

        <div class="reminder-preview">
          <h4>提醒预览：</h4>
          <div class="preview-message">
            {{ getPreviewMessage() }}
          </div>
        </div>

        <div
          class="reminder-debug"
          style="
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
          "
        >
          <h4>调试信息：</h4>
          <div class="debug-info">
            <p><strong>已提醒日程数量：</strong>{{ remindedSchedules.size }}</p>
            <p><strong>检查间隔：</strong>{{ reminderCheckInterval }}秒</p>
            <p>
              <strong>浏览器通知权限：</strong
              >{{ getNotificationPermissionStatus() }}
            </p>
            <p><strong>总日程数：</strong>{{ schedules.length }}</p>
            <p><strong>进行中日程：</strong>{{ getActiveSchedulesCount() }}</p>
            <p><strong>未开始日程：</strong>{{ getPendingSchedulesCount() }}</p>
            <p>
              <strong>已结束日程：</strong>{{ getCompletedSchedulesCount() }}
            </p>
            <el-button size="mini" type="info" @click="showDebugInfo"
              >查看详细调试信息</el-button
            >
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reminderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveReminderSettings"
          >保存设置</el-button
        >
      </span>
    </el-dialog>

    <!-- 日程优化对话框 -->
    <el-dialog
      title="智能日程优化"
      :visible.sync="optimizeDialogVisible"
      width="50%"
      :close-on-click-modal="true"
      :append-to-body="true"
    >
      <div class="optimize-content">
        <div class="optimize-analysis">
          <h4>日程分析结果：</h4>
          <div class="analysis-items">
            <div
              class="analysis-item"
              v-for="(item, index) in optimizeAnalysis"
              :key="index"
            >
              <el-tag :type="item.type" size="small">{{ item.label }}</el-tag>
              <span class="analysis-text">{{ item.text }}</span>
            </div>
          </div>
        </div>

        <div class="optimize-suggestions">
          <h4>优化建议：</h4>
          <el-card
            v-for="(suggestion, index) in optimizeSuggestions"
            :key="index"
            class="suggestion-card"
          >
            <div class="suggestion-header">
              <i :class="suggestion.icon"></i>
              <span class="suggestion-title">{{ suggestion.title }}</span>
              <el-tag :type="suggestion.priority" size="mini">{{
                suggestion.priorityText
              }}</el-tag>
            </div>
            <div class="suggestion-content">
              {{ suggestion.content }}
            </div>
            <div class="suggestion-actions">
              <el-button
                size="mini"
                type="primary"
                @click="applyOptimization(suggestion)"
                >应用</el-button
              >
              <el-button
                size="mini"
                type="info"
                @click="ignoreOptimization(suggestion)"
                >忽略</el-button
              >
            </div>
          </el-card>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="optimizeDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="applyAllOptimizations"
          >应用所有建议</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSchedule,
  getSchedule,
  addSchedule,
  updateSchedule,
  delSchedule,
  delScheduleBatch,
} from "@/api/system/schedule";
import { getCompletion } from "@/api/ai";
import { generateAnswerWithRetry } from "@/api/ollama.js";
import { mapActions } from "vuex";

export default {
  name: "Schedule",
  data() {
    return {
      currentDate: new Date(),
      selectedDate: new Date(),
      schedules: [],
      dialogVisible: false,
      dialogTitle: "添加日程",
      scheduleForm: {
        id: "",
        title: "",
        startTime: "",
        endTime: "",
        remind: "",
        color: "#409EFF",
        description: "",
      },
      remindOptions: [
        { value: "none", label: "不提醒" },
        { value: "1min", label: "提前1分钟" },
        { value: "5min", label: "提前5分钟" },
        { value: "15min", label: "提前15分钟" },
        { value: "30min", label: "提前30分钟" },
        { value: "1hour", label: "提前1小时" },
        { value: "1day", label: "提前1天" },
      ],
      isEdit: false,
      showAiAssistant: true,
      aiInputMessage: "",
      aiMessages: [],
      aiSuggestions: [],
      aiLoading: false,
      listViewType: "all",
      countdownTimer: null,
      notificationTimer: null,
      // 新增：实时刷新相关配置
      realtimeUpdateTimer: null,
      realtimeUpdateInterval: 1000, // 1秒更新一次
      lastUpdateTime: new Date(),
      upcomingSchedulesCache: [],
      // 新增：页面可见性相关
      isPageVisible: true,
      // 新增：实时更新统计
      updateStats: {
        totalUpdates: 0,
        lastUpdateDuration: 0,
        averageUpdateTime: 0,
      },
      // 新增：AI服务状态
      aiServiceStatus: {
        type: 'info',
        text: '检查中',
        icon: 'el-icon-loading',
        message: '正在检查AI服务状态...'
      },
      reminderDialogVisible: false,
      reminderSettings: {
        browserNotification: true,
        soundNotification: true,
        defaultRemindTime: "5min",
        smartRules: ["conflict", "overlap"],
        messageTemplate: "{title} 将在 {time} 开始，请做好准备！",
      },
      optimizeDialogVisible: false,
      optimizeAnalysis: [],
      optimizeSuggestions: [],
      showScrollToBottom: false,
      remindedSchedules: new Set(),
      reminderCheckInterval: 30,
      refreshing: false,
      scheduleFormRules: {
        title: [
          { required: true, message: "请输入日程标题", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur",
          },
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "change" },
        ],
        remind: [
          { required: true, message: "请选择提醒时间", trigger: "change" },
        ],
      },
      now: new Date(), // 新增：用于驱动倒计时实时刷新
      selectedModel: "liudong", // 新增，默认模型
    };
  },
  created() {
    this.loadSchedules();
    this.startCountdownTimer();
    this.startNotificationTimer();
    this.startRealtimeUpdateTimer(); // 新增：启动实时刷新定时器
    this.loadReminderSettings();
    this.requestNotificationPermission();
    this.setupPageVisibilityListener(); // 新增：设置页面可见性监听
    this.initAiServiceStatus(); // 新增：初始化AI服务状态
    // 新增：每秒更新时间，驱动倒计时刷新
    this._nowTimer = setInterval(() => {
      this.now = new Date();
    }, 1000);
    // 添加AI助手欢迎消息
    this.aiMessages.push({
      role: "assistant",
      content:
        "您好！我是您的智能日程管理助手，可以帮您安排日程、优化时间、设置提醒等。有什么需要帮助的吗？",
    });
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
    if (this.notificationTimer) {
      clearInterval(this.notificationTimer);
    }
    if (this.realtimeUpdateTimer) {
      clearInterval(this.realtimeUpdateTimer);
    }
    // 新增：清理now定时器
    if (this._nowTimer) {
      clearInterval(this._nowTimer);
    }
  },
  computed: {
    filteredSchedules() {
      const now = new Date();

      if (this.listViewType === "all") {
        // 显示全部日程
        return this.schedules
          .sort((a, b) => new Date(a.startTime) - new Date(b.startTime));
      } else if (this.listViewType === "week") {
        // 显示本周日程 - 以周一为第一天
        const weekStart = this.getWeekStart();
        const weekEnd = this.getWeekEnd();

        return this.schedules
          .filter((item) => {
            const startTime = new Date(item.startTime);
            return startTime >= weekStart && startTime <= weekEnd;
          })
          .sort((a, b) => new Date(a.startTime) - new Date(b.startTime));
      } else {
        // 显示本月日程
        const monthStart = this.getMonthStart();
        const monthEnd = this.getMonthEnd();

        return this.schedules
          .filter((item) => {
            const startTime = new Date(item.startTime);
            return startTime >= monthStart && startTime <= monthEnd;
          })
          .sort((a, b) => new Date(a.startTime) - new Date(b.startTime));
      }
    },
    endTimePickerOptions() {
      return {
        disabledDate: (time) => {
          if (!this.scheduleForm.startTime) {
            return false; // 如果没有选择开始时间，不禁用任何日期
          }
          const startTime = new Date(this.scheduleForm.startTime);
          return time.getTime() <= startTime.getTime();
        },
      };
    },
    upcomingSchedules() {
      const now = this.now; // 用响应式的now
      const schedules = this.schedules
        .filter((item) => {
          const startTime = new Date(item.startTime);
          const endTime = new Date(item.endTime);
          // 显示即将开始或正在进行的日程
          return startTime > now || (startTime <= now && endTime > now);
        })
        .map((item) => {
          const startTime = new Date(item.startTime);
          const endTime = new Date(item.endTime);
          const isUrgent = startTime <= now && endTime > now;
          const countdownText = this.getCountdownText(startTime, endTime, now); // 传入now
          const timeUntilStart = Math.max(0, startTime - now);
          const timeUntilEnd = Math.max(0, endTime - now);
          const isStartingSoon = timeUntilStart <= 5 * 60 * 1000; // 5分钟内开始
          const isEndingSoon = timeUntilEnd <= 5 * 60 * 1000; // 5分钟内结束

          return {
            ...item,
            isUrgent,
            countdownText,
            timeUntilStart,
            timeUntilEnd,
            isStartingSoon,
            isEndingSoon,
            // 新增：用于强制更新的时间戳
            updateTimestamp: now.getTime(),
          };
        })
        .sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
        .slice(0, 5); // 只显示前5个

      // 缓存结果用于比较
      this.upcomingSchedulesCache = schedules;
      return schedules;
    },
  },
  methods: {
    ...mapActions("ai", ["incrementAiCallCount"]),

    loadSchedules() {
      listSchedule()
        .then((response) => {
          this.schedules = response.rows;
          this.updateScheduleCountdowns();
          // 清理过期的提醒记录
          this.cleanupExpiredReminders();
        })
        .catch((error) => {
          console.error("加载日程失败:", error);
          this.$message.error("加载日程数据失败");
        });
    },

    cleanupExpiredReminders() {
      const now = new Date();
      const keysToDelete = [];

      this.remindedSchedules.forEach((key) => {
        const parts = key.split("_");
        const scheduleId = parts[0];
        const schedule = this.schedules.find((s) => s.id == scheduleId);

        if (schedule) {
          const startTime = new Date(schedule.startTime);
          const endTime = new Date(schedule.endTime);

          // 如果日程已经结束或已经开始，清理记录
          if (endTime <= now || startTime <= now) {
            keysToDelete.push(key);
          }
        } else {
          // 如果日程不存在，清理记录
          keysToDelete.push(key);
        }
      });

      keysToDelete.forEach((key) => this.remindedSchedules.delete(key));
    },

    getWeekStart() {
      const now = new Date();
      const dayOfWeek = now.getDay(); // 0是周日，1是周一，...，6是周六
      const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // 计算到周一的天数
      const weekStart = new Date(now);
      weekStart.setDate(now.getDate() - daysToMonday);
      weekStart.setHours(0, 0, 0, 0);
      return weekStart;
    },

    getWeekEnd() {
      const weekStart = this.getWeekStart();
      const weekEnd = new Date(weekStart);
      weekEnd.setDate(weekStart.getDate() + 6);
      weekEnd.setHours(23, 59, 59, 999);
      return weekEnd;
    },

    getMonthStart() {
      const now = new Date();
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      monthStart.setHours(0, 0, 0, 0);
      return monthStart;
    },

    getMonthEnd() {
      const now = new Date();
      const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      monthEnd.setHours(23, 59, 59, 999);
      return monthEnd;
    },

    formatDateRange(startDate, endDate) {
      const formatDate = (date) => {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(date.getDate()).padStart(2, "0")}`;
      };
      return `${formatDate(startDate)} 至 ${formatDate(endDate)}`;
    },

    getSchedulesByDate(date) {
      return this.schedules.filter((item) => {
        const itemDate = new Date(item.startTime);
        return (
          itemDate.getFullYear() === date.getFullYear() &&
          itemDate.getMonth() === date.getMonth() &&
          itemDate.getDate() === date.getDate()
        );
      });
    },

    showAddDialog() {
      this.dialogTitle = "添加日程";
      this.isEdit = false;
      this.scheduleForm = {
        id: "",
        title: "",
        startTime: "",
        endTime: "",
        remind: "",
        color: "#409EFF",
        description: "",
      };
      this.dialogVisible = true;
    },

    showDetail(item) {
      this.dialogTitle = "日程详情";
      this.isEdit = true;
      this.scheduleForm = JSON.parse(JSON.stringify(item));
      this.dialogVisible = true;
      // 更新选中日期
      this.selectedDate = new Date(item.startTime);
    },

    saveSchedule() {
      // 确保颜色值有效
      if (!this.scheduleForm.color) {
        this.scheduleForm.color = "#409EFF";
      }

      // 如果没有设置提醒，使用默认提醒设置
      if (!this.scheduleForm.remind) {
        this.scheduleForm.remind = this.reminderSettings.defaultRemindTime;
      }

      // 使用表单验证
      this.$refs.scheduleForm.validate((valid) => {
        if (valid) {
          // 额外验证结束时间是否大于开始时间
          const startTime = new Date(this.scheduleForm.startTime);
          const endTime = new Date(this.scheduleForm.endTime);

          if (endTime <= startTime) {
            this.$message.error("结束时间不能小于或等于开始时间，请重新选择");
            return;
          }

          if (this.isEdit) {
            updateSchedule(this.scheduleForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.loadSchedules();
              // 清理相关提醒记录
              this.clearReminderRecord(this.scheduleForm.id);
            });
          } else {
            addSchedule(this.scheduleForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.loadSchedules();
            });
          }
        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },

    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除该日程？")
        .then(() => {
          delScheduleBatch([row.id]).then(() => {
            this.$modal.msgSuccess("删除成功");
            this.loadSchedules();
            // 清理相关提醒记录
            this.clearReminderRecord(row.id);
          });
        })
        .catch(() => {});
    },

    clearReminderRecord(scheduleId) {
      // 清理指定日程的所有提醒记录
      const keysToDelete = [];
      this.remindedSchedules.forEach((key) => {
        if (key.startsWith(`${scheduleId}_`)) {
          keysToDelete.push(key);
        }
      });
      keysToDelete.forEach((key) => this.remindedSchedules.delete(key));
    },

    handleDateSelect(date) {
      this.selectedDate = date;
    },

    parseTime(time) {
      if (!time) return "";
      const date = new Date(time);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")} ${String(
        date.getHours()
      ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
    },

    getRemindLabel(remind) {
      const option = this.remindOptions.find((item) => item.value === remind);
      return option ? option.label : "不提醒";
    },

    toggleAiAssistant() {
      this.showAiAssistant = !this.showAiAssistant;
    },

    async sendAiMessage() {
      if (!this.aiInputMessage.trim() || this.aiLoading) return;

      try {
        this.aiLoading = true;
        const userMessage = this.aiInputMessage;

        // 添加用户消息
        this.aiMessages.push({
          role: "user",
          content: userMessage,
        });

        this.aiInputMessage = "";

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });

        // 显示AI正在思考的提示
        const thinkingMessage = {
          role: "assistant",
          content: "正在思考中，请稍候...",
          isThinking: true
        };
        this.aiMessages.push(thinkingMessage);

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });

        // 构建AI提示词，包含当前日程信息
        const scheduleContext = this.buildScheduleContext();
        const aiPrompt = `你是一个智能日程管理助手。以下是用户的日程信息：\n\n${scheduleContext}\n\n用户需求：${userMessage}\n\n请根据用户的需求和当前日程情况，提供智能建议和帮助。可以包括：\n1. 日程安排建议\n2. 时间冲突提醒\n3. 日程优化建议\n4. 其他相关建议\n\n如果用户需要创建新日程，请按照以下格式提供建议：\n"建议创建一个日程，标题为"具体标题"，时间在14:30到15:30，描述：具体描述内容"\n\n或者：\n"可以安排一个会议，标题为"会议名称"，明天14:30开始，描述：会议内容"\n\n请用中文回复，并尽可能提供具体的、可操作的建议。如果建议创建日程，请确保包含明确的标题和时间信息。`;

        let response;
        if (this.selectedModel === "ollma") {
          // 调用ollama.js
          response = await generateAnswerWithRetry("deepseek-r1:1.5b", aiPrompt, 2);
        } else {
          // 调用ai.js，模型参数写死为Qwen/Qwen2.5-7B-Instruct
          response = await getCompletion({
            model: "Qwen/Qwen2.5-7B-Instruct",
            message: aiPrompt
          });
        }

        // 移除思考中的消息
        const thinkingIndex = this.aiMessages.findIndex(msg => msg.isThinking);
        if (thinkingIndex > -1) {
          this.aiMessages.splice(thinkingIndex, 1);
        }

        // 兼容两种返回格式
        let content = "";
        if (response.result && response.result.output && response.result.output.content) {
          content = response.result.output.content;
        } else if (response.data && response.data.result && response.data.result.output && response.data.result.output.content) {
          content = response.data.result.output.content;
        } else if (response.content) {
          content = response.content;
        }
        // 去除 <think> 标签及其内容及前后空白
        content = content.replace(/\s*<think>[\s\S]*?<\/think>\s*/gi, "");

        // 添加AI回复
        this.aiMessages.push({
          role: "assistant",
          content: content,
        });

        // 解析AI回复，提取建议
        this.parseAiSuggestions(content);

        // 更新AI调用次数
        this.incrementAiCallCount();

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } catch (error) {
        console.error("AI调用错误:", error);
        
        // 移除思考中的消息
        const thinkingIndex = this.aiMessages.findIndex(msg => msg.isThinking);
        if (thinkingIndex > -1) {
          this.aiMessages.splice(thinkingIndex, 1);
        }

        // 根据错误类型显示不同的提示信息
        let errorMessage = "AI服务暂时不可用，请稍后重试";
        
        if (error.message && error.message.includes("超时")) {
          errorMessage = "AI生成超时，请尝试简化问题或稍后重试";
        } else if (error.message && error.message.includes("网络")) {
          errorMessage = "网络连接异常，请检查网络后重试";
        } else if (error.message && error.message.includes("AI服务")) {
          errorMessage = "AI服务异常，请稍后重试";
        }

        // 添加错误提示消息
        this.aiMessages.push({
          role: "assistant",
          content: `抱歉，${errorMessage}。\n\n如果问题持续存在，请：\n1. 检查网络连接\n2. 尝试简化问题描述\n3. 稍后重试`,
          isError: true
        });

        // 显示错误通知
        this.$notify({
          title: "AI助手提示",
          message: errorMessage,
          type: "warning",
          duration: 5000,
          position: "top-right",
        });

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } finally {
        this.aiLoading = false;
      }
    },

    buildScheduleContext() {
      const now = new Date();
      const todaySchedules = this.schedules.filter((item) => {
        const itemDate = new Date(item.startTime);
        return (
          itemDate.getFullYear() === now.getFullYear() &&
          itemDate.getMonth() === now.getMonth() &&
          itemDate.getDate() === now.getDate()
        );
      });

      const upcomingSchedules = this.schedules
        .filter((item) => {
          const startTime = new Date(item.startTime);
          return startTime > now;
        })
        .slice(0, 5);

      let context = `今日日程：\n`;
      if (todaySchedules.length > 0) {
        todaySchedules.forEach((schedule) => {
          context += `- ${schedule.title} (${this.parseTime(
            schedule.startTime
          )} - ${this.parseTime(schedule.endTime)})\n`;
        });
      } else {
        context += `- 暂无日程安排\n`;
      }

      context += `\n即将到来的日程：\n`;
      if (upcomingSchedules.length > 0) {
        upcomingSchedules.forEach((schedule) => {
          context += `- ${schedule.title} (${this.parseTime(
            schedule.startTime
          )})\n`;
        });
      } else {
        context += `- 暂无即将到来的日程\n`;
      }

      return context;
    },

    parseAiSuggestions(content) {
      // 解析AI回复中的日程信息
      const suggestions = [];

      // 尝试解析AI回复中的日程信息
      const scheduleInfo = this.parseScheduleFromAiResponse(content);

      if (scheduleInfo) {
        suggestions.push({
          text: "应用AI建议 - 创建日程",
          type: "primary",
          action: "create_schedule_from_ai",
          data: scheduleInfo,
        });
      }

      if (content.includes("建议") || content.includes("推荐")) {
        suggestions.push({
          text: "应用AI建议",
          type: "primary",
          action: "apply_ai_suggestion",
        });
      }

      if (content.includes("优化") || content.includes("调整")) {
        suggestions.push({
          text: "优化日程安排",
          type: "warning",
          action: "optimize_schedule",
        });
      }

      this.aiSuggestions = suggestions;
    },

    parseScheduleFromAiResponse(content) {
      // 解析AI回复中的日程信息
      let title = "";
      let startTime = "";
      let endTime = "";
      let description = "";

      // 提取标题 - 优先从引号中提取
      const titleMatch = content.match(/["""]([^"""]+)["""]/);
      if (titleMatch) {
        title = titleMatch[1];
      } else {
        // 尝试从其他模式提取标题
        const titlePatterns = [
          /(?:建议|可以|需要)?(?:安排|创建|添加|设置)(?:一个|一个)?(?:会议|日程|活动|任务|提醒)(?:，)?(?:标题为)?([^，。\n]+)/,
          /(?:标题为|名称为)([^，。\n]+)/,
          /(?:创建一个|安排一个)([^，。\n]+)(?:会议|日程|活动|任务)/,
        ];

        for (const pattern of titlePatterns) {
          const match = content.match(pattern);
          if (match) {
            title = match[1].trim();
            break;
          }
        }
      }

      // 提取时间信息 - 支持多种格式
      const timePatterns = [
        // "14:30到15:30" 格式
        /(\d{1,2}:\d{2})(?:到|至|~|-)(\d{1,2}:\d{2})/,
        // "明天14:30" 格式
        /(明天|后天|今天)?(\d{1,2}:\d{2})/,
        // "下午2点到3点" 格式
        /(上午|下午|晚上)?(\d{1,2})点(?:到|至|~|-)(\d{1,2})点/,
        // "14点30分" 格式
        /(\d{1,2})点(\d{0,2})分/,
      ];

      for (const pattern of timePatterns) {
        const match = content.match(pattern);
        if (match) {
          if (match[1] && match[2] && match[3]) {
            // 有开始和结束时间
            startTime = this.parseTimeFromText(match[1] + match[2]);
            endTime = this.parseTimeFromText(match[1] + match[3]);
          } else if (match[1] && match[2]) {
            // 只有开始时间，可能是相对时间+绝对时间
            if (
              match[1] === "明天" ||
              match[1] === "后天" ||
              match[1] === "今天"
            ) {
              startTime = this.parseTimeFromText(match[1] + match[2]);
            } else {
              startTime = this.parseTimeFromText(match[1] + match[2]);
            }
          }
          break;
        }
      }

      // 如果没有找到时间，尝试从文本中提取单个时间
      if (!startTime) {
        const singleTimePatterns = [
          /(明天|后天|今天)?(\d{1,2}:\d{2})/,
          /(上午|下午|晚上)?(\d{1,2})点(\d{0,2})分/,
          /(\d{1,2})点(\d{0,2})分/,
        ];

        for (const pattern of singleTimePatterns) {
          const match = content.match(pattern);
          if (match) {
            // 处理匹配结果
            if (match[1] && match[2]) {
              startTime = this.parseTimeFromText(match[1] + match[2]);
            } else if (match[1]) {
              startTime = this.parseTimeFromText(match[1]);
            }
            break;
          }
        }
      }

      // 提取描述
      const descPatterns = [
        /(?:描述|内容|详情|说明)[：:]\s*([^。\n]+)/,
        /(?:关于|涉及)[：:]\s*([^。\n]+)/,
        /(?:，|。)([^，。\n]{5,})/,
      ];

      for (const pattern of descPatterns) {
        const match = content.match(pattern);
        if (match && match[1].length > 5) {
          description = match[1].trim();
          break;
        }
      }

      // 如果找到了标题和时间，返回日程信息
      if (title && startTime) {
        return {
          title: title,
          startTime: startTime,
          endTime: endTime || this.getDefaultEndTime(startTime),
          description: description,
          color: this.getRandomColor(),
          remind: this.reminderSettings.defaultRemindTime,
        };
      }

      return null;
    },

    parseTimeFromText(timeText) {
      const now = new Date();
      let date = new Date(now);
      let originalText = timeText;

      // 处理相对时间
      if (timeText.includes("明天")) {
        date.setDate(date.getDate() + 1);
        timeText = timeText.replace("明天", "");
      } else if (timeText.includes("后天")) {
        date.setDate(date.getDate() + 2);
        timeText = timeText.replace("后天", "");
      } else if (timeText.includes("今天")) {
        timeText = timeText.replace("今天", "");
      }

      // 处理 "14:30" 格式
      if (timeText.includes(":")) {
        const timeMatch = timeText.match(/(\d{1,2}):(\d{2})/);
        if (timeMatch) {
          const hours = parseInt(timeMatch[1]);
          const minutes = parseInt(timeMatch[2]);
          date.setHours(hours, minutes, 0, 0);
        }
      }
      // 处理 "14点30分" 格式
      else if (timeText.includes("点")) {
        const hourMatch = timeText.match(/(\d+)点/);
        const minuteMatch = timeText.match(/(\d+)分/);
        if (hourMatch) {
          const hours = parseInt(hourMatch[1]);
          const minutes = minuteMatch ? parseInt(minuteMatch[1]) : 0;
          date.setHours(hours, minutes, 0, 0);
        }
      }
      // 处理 "下午2点" 格式
      else if (timeText.includes("下午") || timeText.includes("晚上")) {
        const hourMatch = timeText.match(/(\d+)点/);
        if (hourMatch) {
          let hours = parseInt(hourMatch[1]);
          if (hours < 12) {
            hours += 12; // 下午/晚上时间加12
          }
          const minuteMatch = timeText.match(/(\d+)分/);
          const minutes = minuteMatch ? parseInt(minuteMatch[1]) : 0;
          date.setHours(hours, minutes, 0, 0);
        }
      }
      // 处理 "上午10点" 格式
      else if (timeText.includes("上午") || timeText.includes("早上")) {
        const hourMatch = timeText.match(/(\d+)点/);
        if (hourMatch) {
          let hours = parseInt(hourMatch[1]);
          if (hours === 12) {
            hours = 0; // 上午12点就是0点
          }
          const minuteMatch = timeText.match(/(\d+)分/);
          const minutes = minuteMatch ? parseInt(minuteMatch[1]) : 0;
          date.setHours(hours, minutes, 0, 0);
        }
      }

      // 如果没有解析到有效时间，尝试从原始文本重新解析
      if (
        date.getHours() === now.getHours() &&
        date.getMinutes() === now.getMinutes()
      ) {
        // 尝试从原始文本中提取时间
        const timeMatch = originalText.match(/(\d{1,2}):(\d{2})/);
        if (timeMatch) {
          const hours = parseInt(timeMatch[1]);
          const minutes = parseInt(timeMatch[2]);
          date.setHours(hours, minutes, 0, 0);
        }
      }

      return date.toISOString();
    },

    getDefaultEndTime(startTime) {
      const startDate = new Date(startTime);
      startDate.setHours(startDate.getHours() + 1);
      return startDate.toISOString();
    },

    getRandomColor() {
      const colors = [
        "#409EFF",
        "#67C23A",
        "#E6A23C",
        "#F56C6C",
        "#909399",
        "#9C27B0",
        "#FF9800",
        "#4CAF50",
      ];
      return colors[Math.floor(Math.random() * colors.length)];
    },

    applySuggestion(suggestion) {
      switch (suggestion.action) {
        case "create_schedule_from_ai":
          this.createScheduleFromAiSuggestion(suggestion.data);
          break;
        case "apply_ai_suggestion":
          this.$message.success("AI建议已应用");
          break;
        case "optimize_schedule":
          this.optimizeSchedule();
          break;
        default:
          this.$message.info("功能开发中");
      }
    },

    createScheduleFromAiSuggestion(scheduleData) {
      // 优化：只要是当前时间之后，并随机生成一个合理的时间段
      const now = new Date();
      // 随机生成未来5~120分钟内的开始时间
      const randomMinutes = Math.floor(Math.random() * 116) + 5; // 5~120分钟
      const startTime = new Date(now.getTime() + randomMinutes * 60 * 1000);
      // 随机生成30~120分钟的持续时间
      const randomDuration = Math.floor(Math.random() * 91) + 30; // 30~120分钟
      const endTime = new Date(startTime.getTime() + randomDuration * 60 * 1000);
      scheduleData.startTime = startTime.toISOString();
      scheduleData.endTime = endTime.toISOString();
      // 显示确认对话框
      this.$confirm(
        `确定要创建以下日程吗？\n\n标题：${
          scheduleData.title
        }\n开始时间：${this.parseTime(
          scheduleData.startTime
        )}\n结束时间：${this.parseTime(scheduleData.endTime)}${
          scheduleData.description ? `\n描述：${scheduleData.description}` : ""
        }`,
        "确认创建日程",
        {
          confirmButtonText: "创建",
          cancelButtonText: "取消",
          type: "info",
          center: true,
        }
      )
        .then(() => {
          // 用户确认创建
          addSchedule(scheduleData)
            .then((response) => {
              this.$modal.msgSuccess("日程创建成功！");
              this.loadSchedules();

              // 显示创建成功的通知
              this.$notify({
                title: "AI建议已应用",
                message: `已成功创建日程："${scheduleData.title}"`,
                type: "success",
                duration: 5000,
                position: "top-right",
              });
            })
            .catch((error) => {
              console.error("创建日程失败:", error);
              this.$message.error("创建日程失败，请重试");
            });
        })
        .catch(() => {
          // 用户取消
          this.$message.info("已取消创建日程");
        });
    },

    optimizeSchedule() {
      this.optimizeDialogVisible = true;
      this.analyzeSchedule();
    },

    getPreviewMessage() {
      const template = this.reminderSettings.messageTemplate;
      return template
        .replace("{title}", "示例日程")
        .replace("{time}", "14:30")
        .replace("{duration}", "1小时");
    },

    loadReminderSettings() {
      const saved = localStorage.getItem("reminderSettings");
      if (saved) {
        this.reminderSettings = {
          ...this.reminderSettings,
          ...JSON.parse(saved),
        };
      }
    },

    saveReminderSettings() {
      localStorage.setItem(
        "reminderSettings",
        JSON.stringify(this.reminderSettings)
      );
      this.$message.success("提醒设置已保存");
      this.reminderDialogVisible = false;
    },

    async requestNotificationPermission() {
      if ("Notification" in window && Notification.permission === "default") {
        const permission = await Notification.requestPermission();
        if (permission === "granted") {
          this.reminderSettings.browserNotification = true;
        }
      }
    },

    testNotification() {
      const testSchedule = {
        id: "test",
        title: "测试日程",
        startTime: new Date(Date.now() + 30 * 60 * 1000).toISOString(), // 30分钟后
        endTime: new Date(Date.now() + 90 * 60 * 1000).toISOString(), // 90分钟后
        description: "这是一个测试日程，用于验证提醒功能是否正常工作。",
        remind: "5min",
      };

      if (
        this.reminderSettings.browserNotification &&
        Notification.permission === "granted"
      ) {
        const message = this.generateReminderMessage(testSchedule, "5min");
        new Notification("测试通知", {
          body: message,
          icon: "/favicon.ico",
          requireInteraction: true,
        });
      }

      this.$notify({
        title: "测试通知",
        message: this.generateReminderMessage(testSchedule, "5min"),
        type: "success",
        duration: 5000,
        customClass: "schedule-reminder-notification",
      });

      if (this.reminderSettings.soundNotification) {
        this.playNotificationSound();
      }
    },

    playNotificationSound() {
      // 创建音频元素播放提示音
      const audio = new Audio(
        "data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBC13yO/eizEIHWq+8+OWT"
      );
      audio.play().catch(() => {
        // 忽略播放错误
      });
    },

    analyzeSchedule() {
      this.optimizeAnalysis = [];
      this.optimizeSuggestions = [];

      const now = new Date();
      const todaySchedules = this.schedules.filter((item) => {
        const itemDate = new Date(item.startTime);
        return (
          itemDate.getFullYear() === now.getFullYear() &&
          itemDate.getMonth() === now.getMonth() &&
          itemDate.getDate() === now.getDate()
        );
      });

      // 分析时间冲突
      const conflicts = this.findTimeConflicts(todaySchedules);
      if (conflicts.length > 0) {
        this.optimizeAnalysis.push({
          type: "warning",
          label: "时间冲突",
          text: `发现 ${conflicts.length} 个时间冲突`,
        });

        conflicts.forEach((conflict) => {
          this.optimizeSuggestions.push({
            icon: "el-icon-warning",
            title: "解决时间冲突",
            content: `"${conflict.schedule1.title}" 与 "${conflict.schedule2.title}" 时间冲突，建议调整其中一个的时间`,
            priority: "warning",
            priorityText: "高优先级",
            action: "resolve_conflict",
            data: conflict,
          });
        });
      }

      // 分析日程密度
      const density = this.analyzeScheduleDensity(todaySchedules);
      if (density > 0.8) {
        this.optimizeAnalysis.push({
          type: "info",
          label: "日程密集",
          text: `今日日程密度较高 (${Math.round(density * 100)}%)`,
        });

        this.optimizeSuggestions.push({
          icon: "el-icon-time",
          title: "优化日程安排",
          content: "今日日程安排较为密集，建议适当调整时间间隔，预留休息时间",
          priority: "info",
          priorityText: "中优先级",
          action: "optimize_density",
        });
      }

      // 分析空闲时间
      const gaps = this.findFreeTimeGaps(todaySchedules);
      if (gaps.length > 0) {
        this.optimizeAnalysis.push({
          type: "success",
          label: "空闲时间",
          text: `发现 ${gaps.length} 个空闲时间段`,
        });

        gaps.forEach((gap) => {
          this.optimizeSuggestions.push({
            icon: "el-icon-plus",
            title: "利用空闲时间",
            content: `在 ${this.formatTimeDisplay(
              gap.start
            )} - ${this.formatTimeDisplay(gap.end)} 期间可以安排其他活动`,
            priority: "success",
            priorityText: "建议",
            action: "use_free_time",
            data: gap,
          });
        });
      }

      // 如果没有问题，显示正面反馈
      if (this.optimizeAnalysis.length === 0) {
        this.optimizeAnalysis.push({
          type: "success",
          label: "日程良好",
          text: "您的日程安排合理，没有发现明显问题",
        });
      }
    },

    findTimeConflicts(schedules) {
      const conflicts = [];
      for (let i = 0; i < schedules.length; i++) {
        for (let j = i + 1; j < schedules.length; j++) {
          const s1 = schedules[i];
          const s2 = schedules[j];
          const start1 = new Date(s1.startTime);
          const end1 = new Date(s1.endTime);
          const start2 = new Date(s2.startTime);
          const end2 = new Date(s2.endTime);

          if (start1 < end2 && start2 < end1) {
            conflicts.push({
              schedule1: s1,
              schedule2: s2,
              overlap: Math.min(end1, end2) - Math.max(start1, start2),
            });
          }
        }
      }
      return conflicts;
    },

    analyzeScheduleDensity(schedules) {
      if (schedules.length === 0) return 0;

      const workHours = 8; // 假设工作时间8小时
      const totalMinutes = workHours * 60;
      let busyMinutes = 0;

      schedules.forEach((schedule) => {
        const start = new Date(schedule.startTime);
        const end = new Date(schedule.endTime);
        busyMinutes += (end - start) / (1000 * 60);
      });

      return Math.min(busyMinutes / totalMinutes, 1);
    },

    findFreeTimeGaps(schedules) {
      const gaps = [];
      const workStart = new Date();
      workStart.setHours(9, 0, 0, 0); // 假设工作开始时间9点
      const workEnd = new Date();
      workEnd.setHours(18, 0, 0, 0); // 假设工作结束时间18点

      // 按开始时间排序
      const sortedSchedules = [...schedules].sort(
        (a, b) => new Date(a.startTime) - new Date(b.startTime)
      );

      let currentTime = workStart;

      sortedSchedules.forEach((schedule) => {
        const scheduleStart = new Date(schedule.startTime);
        if (scheduleStart > currentTime) {
          gaps.push({
            start: currentTime,
            end: scheduleStart,
          });
        }
        currentTime = new Date(schedule.endTime);
      });

      // 检查最后一个日程后的时间
      if (currentTime < workEnd) {
        gaps.push({
          start: currentTime,
          end: workEnd,
        });
      }

      // 过滤掉太短的间隙（少于30分钟）
      return gaps.filter((gap) => (gap.end - gap.start) / (1000 * 60) >= 30);
    },

    formatTime(milliseconds) {
      const seconds = Math.floor(milliseconds / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);

      if (days > 0) return `${days}天${hours % 24}小时`;
      if (hours > 0) return `${hours}小时${minutes % 60}分钟`;
      if (minutes > 0) return `${minutes}分钟`;
      return `${seconds}秒`;
    },

    formatTimeDisplay(date) {
      return `${String(date.getHours()).padStart(2, "0")}:${String(
        date.getMinutes()
      ).padStart(2, "0")}`;
    },

    applyOptimization(suggestion) {
      switch (suggestion.action) {
        case "resolve_conflict":
          this.resolveTimeConflict(suggestion.data);
          break;
        case "optimize_density":
          this.optimizeScheduleDensity();
          break;
        case "use_free_time":
          this.useFreeTime(suggestion.data);
          break;
        default:
          this.$message.info("功能开发中");
      }

      // 从建议列表中移除
      const index = this.optimizeSuggestions.indexOf(suggestion);
      if (index > -1) {
        this.optimizeSuggestions.splice(index, 1);
      }
    },

    ignoreOptimization(suggestion) {
      const index = this.optimizeSuggestions.indexOf(suggestion);
      if (index > -1) {
        this.optimizeSuggestions.splice(index, 1);
      }
      this.$message.info("已忽略该建议");
    },

    applyAllOptimizations() {
      const suggestions = [...this.optimizeSuggestions];
      suggestions.forEach((suggestion) => {
        this.applyOptimization(suggestion);
      });
      this.$message.success("已应用所有优化建议");
    },

    resolveTimeConflict(conflict) {
      // 简单的冲突解决：将第二个日程延后
      const schedule = conflict.schedule2;
      const originalStart = new Date(schedule.startTime);
      const originalEnd = new Date(schedule.endTime);
      const duration = originalEnd - originalStart;

      // 延后到第一个日程结束后
      const newStart = new Date(conflict.schedule1.endTime);
      const newEnd = new Date(newStart.getTime() + duration);

      schedule.startTime = newStart.toISOString();
      schedule.endTime = newEnd.toISOString();

      updateSchedule(schedule).then(() => {
        this.$message.success("时间冲突已解决");
        this.loadSchedules();
      });
    },

    optimizeScheduleDensity() {
      this.$message.info("日程密度优化功能开发中");
    },

    useFreeTime(gap) {
      // 优化：只要是当前时间之后，并随机生成一个合理的时间段
      const now = new Date();
      // 随机生成未来5~60分钟内的开始时间
      const randomMinutes = Math.floor(Math.random() * 56) + 5; // 5~60分钟
      const startTime = new Date(now.getTime() + randomMinutes * 60 * 1000);
      // 随机生成30~90分钟的持续时间
      const randomDuration = Math.floor(Math.random() * 61) + 30; // 30~90分钟
      const endTime = new Date(startTime.getTime() + randomDuration * 60 * 1000);
      const reminder = {
        title: "休息时间",
        startTime: startTime.toISOString(),
        endTime: endTime.toISOString(),
        color: "#67c23a",
        description: "建议利用这段时间休息或处理其他事务",
        remind: "5min",
      };
      addSchedule(reminder).then(() => {
        this.$message.success("已在空闲时间添加提醒");
        this.loadSchedules();
      });
    },

    getCountdownText(startTime, endTime, nowArg) {
      // 新增：支持传入now参数，默认用this.now
      const now = nowArg || this.now;
      const startDiff = Math.max(0, startTime - now);
      const endDiff = Math.max(0, endTime - now);

      if (startTime <= now && endTime > now) {
        // 正在进行中
        if (endDiff <= 30 * 1000) {
          // 30秒内结束
          return `即将结束 (剩余${Math.ceil(endDiff / 1000)}秒)`;
        } else if (endDiff <= 60 * 1000) {
          // 1分钟内结束
          return `即将结束 (剩余${Math.ceil(endDiff / 1000)}秒)`;
        } else if (endDiff <= 5 * 60 * 1000) {
          // 5分钟内结束
          return `即将结束 (剩余${Math.ceil(endDiff / (60 * 1000))}分钟)`;
        } else {
          return `进行中 (剩余${this.formatTime(endDiff)})`;
        }
      } else {
        // 未开始
        if (startDiff <= 30 * 1000) {
          // 30秒内开始
          return `即将开始 (剩余${Math.ceil(startDiff / 1000)}秒)`;
        } else if (startDiff <= 60 * 1000) {
          // 1分钟内开始
          return `即将开始 (剩余${Math.ceil(startDiff / 1000)}秒)`;
        } else if (startDiff <= 5 * 60 * 1000) {
          // 5分钟内开始
          return `即将开始 (剩余${Math.ceil(startDiff / (60 * 1000))}分钟)`;
        } else if (startDiff <= 60 * 60 * 1000) {
          // 1小时内开始
          const minutes = Math.ceil(startDiff / (60 * 1000));
          return `还有${minutes}分钟`;
        } else if (startDiff <= 24 * 60 * 60 * 1000) {
          // 24小时内开始
          const hours = Math.ceil(startDiff / (60 * 60 * 1000));
          return `还有${hours}小时`;
        } else {
          return `还有${this.formatTime(startDiff)}`;
        }
      }
    },

    getScheduleStatus(schedule) {
      const now = new Date();
      const startTime = new Date(schedule.startTime);
      const endTime = new Date(schedule.endTime);

      if (startTime <= now && endTime > now) {
        return {
          type: "warning",
          text: "进行中",
        };
      } else if (startTime > now) {
        return {
          type: "info",
          text: "未开始",
        };
      } else {
        return {
          type: "success",
          text: "已结束",
        };
      }
    },

    startCountdownTimer() {
      // 每秒更新倒计时，提高实时性
      this.countdownTimer = setInterval(() => {
        this.updateScheduleCountdowns();
      }, 1000);
    },

    startNotificationTimer() {
      // 每10秒检查提醒，提高提醒精度
      this.notificationTimer = setInterval(() => {
        this.checkReminders();
      }, 10 * 1000); // 改为10秒检查一次
    },

    updateScheduleCountdowns() {
      // 强制更新计算属性，确保倒计时实时更新
      this.$forceUpdate();
    },

    checkReminders() {
      const now = new Date();
      let checkedCount = 0;
      let triggeredCount = 0;

      this.schedules.forEach((schedule) => {
        // 获取提醒类型，如果没有设置则使用默认值
        const remindType =
          schedule.remind || this.reminderSettings.defaultRemindTime;

        if (remindType && remindType !== "none") {
          const startTime = new Date(schedule.startTime);
          const endTime = new Date(schedule.endTime);

          // 检查日程是否已经结束，如果已结束则不提醒
          if (endTime <= now) {
            return;
          }

          // 检查日程是否已经开始，如果已开始则不提醒
          if (startTime <= now) {
            return;
          }

          checkedCount++;

          // 计算距离开始时间还有多少分钟
          const minutesUntilStart = Math.floor((startTime - now) / (1000 * 60));

          // 根据不同的提醒类型处理
          const triggered = this.handleReminderByType(
            schedule,
            remindType,
            minutesUntilStart,
            now
          );
          if (triggered) {
            triggeredCount++;
          }
        }
      });

      // 调试信息
      if (checkedCount > 0) {
        console.log(
          `[提醒检查] 检查了 ${checkedCount} 个日程，触发了 ${triggeredCount} 个提醒`
        );
      }
    },

    handleReminderByType(schedule, remindType, minutesUntilStart, now) {
      const startTime = new Date(schedule.startTime);
      let triggered = false;

      switch (remindType) {
        case "1min":
          triggered = this.handleOneMinuteReminder(
            schedule,
            minutesUntilStart,
            now
          );
          break;
        case "5min":
          triggered = this.handleFiveMinuteReminder(
            schedule,
            minutesUntilStart,
            now
          );
          break;
        case "15min":
          triggered = this.handleFifteenMinuteReminder(
            schedule,
            minutesUntilStart,
            now
          );
          break;
        case "30min":
          triggered = this.handleThirtyMinuteReminder(
            schedule,
            minutesUntilStart,
            now
          );
          break;
        case "1hour":
          triggered = this.handleOneHourReminder(
            schedule,
            minutesUntilStart,
            now
          );
          break;
        case "1day":
          triggered = this.handleOneDayReminder(
            schedule,
            minutesUntilStart,
            now
          );
          break;
      }

      return triggered;
    },

    handleOneMinuteReminder(schedule, minutesUntilStart, now) {
      // 提前1分钟提醒：在1分钟时提醒一次
      if (minutesUntilStart === 1) {
        this.triggerReminder(schedule, "1min", now);
        return true;
      }
      return false;
    },

    handleFiveMinuteReminder(schedule, minutesUntilStart, now) {
      // 提前5分钟提醒：5分钟前提醒一次，5分钟以内每分钟提醒一次
      if (minutesUntilStart === 5) {
        // 5分钟前提醒一次
        this.triggerReminder(schedule, "5min", now);
        return true;
      } else if (minutesUntilStart >= 1 && minutesUntilStart < 5) {
        // 5分钟以内，每分钟提醒一次
        const reminderKey = `${schedule.id}_5min_${minutesUntilStart}`;
        if (!this.remindedSchedules.has(reminderKey)) {
          this.triggerReminder(
            schedule,
            `5min_${minutesUntilStart}min`,
            now,
            reminderKey
          );
          return true;
        }
      }
      return false;
    },

    handleFifteenMinuteReminder(schedule, minutesUntilStart, now) {
      // 提前15分钟提醒：15分钟前提醒一次，5分钟以内每分钟提醒一次
      if (minutesUntilStart === 15) {
        this.triggerReminder(schedule, "15min", now);
        return true;
      } else if (minutesUntilStart >= 1 && minutesUntilStart < 5) {
        // 5分钟以内，每分钟提醒一次
        const reminderKey = `${schedule.id}_15min_${minutesUntilStart}`;
        if (!this.remindedSchedules.has(reminderKey)) {
          this.triggerReminder(
            schedule,
            `15min_${minutesUntilStart}min`,
            now,
            reminderKey
          );
          return true;
        }
      }
      return false;
    },

    handleThirtyMinuteReminder(schedule, minutesUntilStart, now) {
      // 提前30分钟提醒：30分钟前提醒一次，5分钟以内每分钟提醒一次
      if (minutesUntilStart === 30) {
        this.triggerReminder(schedule, "30min", now);
        return true;
      } else if (minutesUntilStart >= 1 && minutesUntilStart < 5) {
        // 5分钟以内，每分钟提醒一次
        const reminderKey = `${schedule.id}_30min_${minutesUntilStart}`;
        if (!this.remindedSchedules.has(reminderKey)) {
          this.triggerReminder(
            schedule,
            `30min_${minutesUntilStart}min`,
            now,
            reminderKey
          );
          return true;
        }
      }
      return false;
    },

    handleOneHourReminder(schedule, minutesUntilStart, now) {
      // 提前1小时提醒：1小时前提醒一次，5分钟以内每分钟提醒一次
      if (minutesUntilStart === 60) {
        this.triggerReminder(schedule, "1hour", now);
        return true;
      } else if (minutesUntilStart >= 1 && minutesUntilStart < 5) {
        // 5分钟以内，每分钟提醒一次
        const reminderKey = `${schedule.id}_1hour_${minutesUntilStart}`;
        if (!this.remindedSchedules.has(reminderKey)) {
          this.triggerReminder(
            schedule,
            `1hour_${minutesUntilStart}min`,
            now,
            reminderKey
          );
          return true;
        }
      }
      return false;
    },

    handleOneDayReminder(schedule, minutesUntilStart, now) {
      // 提前1天提醒：1天前提醒一次，5分钟以内每分钟提醒一次
      if (minutesUntilStart === 1440) {
        // 24 * 60 = 1440分钟
        this.triggerReminder(schedule, "1day", now);
        return true;
      } else if (minutesUntilStart >= 1 && minutesUntilStart < 5) {
        // 5分钟以内，每分钟提醒一次
        const reminderKey = `${schedule.id}_1day_${minutesUntilStart}`;
        if (!this.remindedSchedules.has(reminderKey)) {
          this.triggerReminder(
            schedule,
            `1day_${minutesUntilStart}min`,
            now,
            reminderKey
          );
          return true;
        }
      }
      return false;
    },

    triggerReminder(schedule, remindType, now, customKey = null) {
      const reminderKey = customKey || `${schedule.id}_${remindType}`;

      // 检查是否已经提醒过
      if (this.remindedSchedules.has(reminderKey)) {
        console.log(
          `[提醒] 日程 "${schedule.title}" 的 ${remindType} 提醒已存在，跳过`
        );
        return;
      }

      // 显示提醒
      this.showNotification(schedule, remindType);

      // 标记为已提醒
      this.remindedSchedules.add(reminderKey);

      console.log(`[提醒] 日程 "${schedule.title}" 已触发 ${remindType} 提醒`);

      // 30分钟后清理提醒记录，避免内存泄漏
      setTimeout(() => {
        this.remindedSchedules.delete(reminderKey);
        console.log(
          `[提醒] 清理日程 "${schedule.title}" 的 ${remindType} 提醒记录`
        );
      }, 30 * 60 * 1000);
    },

    getRemindTime(startTime, remindType) {
      const remindTime = new Date(startTime);

      switch (remindType) {
        case "1min":
          remindTime.setMinutes(remindTime.getMinutes() - 1);
          break;
        case "5min":
          remindTime.setMinutes(remindTime.getMinutes() - 5);
          break;
        case "15min":
          remindTime.setMinutes(remindTime.getMinutes() - 15);
          break;
        case "30min":
          remindTime.setMinutes(remindTime.getMinutes() - 30);
          break;
        case "1hour":
          remindTime.setHours(remindTime.getHours() - 1);
          break;
        case "1day":
          remindTime.setDate(remindTime.getDate() - 1);
          break;
      }

      return remindTime;
    },

    showNotification(schedule, remindType) {
      // 生成提醒消息
      const message = this.generateReminderMessage(schedule, remindType);

      // 使用浏览器通知API
      if (
        this.reminderSettings.browserNotification &&
        "Notification" in window &&
        Notification.permission === "granted"
      ) {
        new Notification("日程提醒", {
          body: message,
          icon: "/favicon.ico",
          tag: `${schedule.id}_${remindType}`,
          requireInteraction: true, // 需要用户交互才关闭
          actions: [
            {
              action: "view",
              title: "查看详情",
            },
            {
              action: "dismiss",
              title: "知道了",
            },
          ],
        });
      }

      // 播放提示音
      if (this.reminderSettings.soundNotification) {
        this.playNotificationSound();
      }

      // 显示Element UI通知弹框
      this.$notify({
        title: "日程提醒",
        message: message,
        type: "warning",
        duration: 0, // 不自动关闭
        showClose: true,
        position: "top-right",
        customClass: "schedule-reminder-notification",
        onClick: () => {
          // 点击通知时显示日程详情
          this.showDetail(schedule);
        },
      });

      // 同时显示确认对话框
      this.$confirm(message, "日程提醒", {
        confirmButtonText: "查看详情",
        cancelButtonText: "知道了",
        type: "warning",
        center: true,
        customClass: "schedule-reminder-dialog",
      })
        .then(() => {
          // 用户点击查看详情
          this.showDetail(schedule);
        })
        .catch(() => {
          // 用户点击知道了，不做任何操作
        });
    },

    generateReminderMessage(schedule, remindType) {
      const startTime = new Date(schedule.startTime);
      const endTime = new Date(schedule.endTime);
      const duration = Math.round((endTime - startTime) / (1000 * 60)); // 分钟

      // 使用消息模板
      let message = this.reminderSettings.messageTemplate;

      // 替换模板变量
      message = message.replace("{title}", schedule.title);
      message = message.replace("{time}", this.formatTimeDisplay(startTime));
      message = message.replace("{duration}", `${duration}分钟`);

      // 处理提醒类型显示
      let remindText = this.getRemindLabel(remindType);

      // 如果是5分钟以内的分钟提醒，显示特殊文本
      if (remindType.includes("_") && remindType.includes("min")) {
        const parts = remindType.split("_");
        const baseType = parts[0];
        const minutesLeft = parts[1];
        remindText = `距离开始还有${minutesLeft}`;
      }

      message += `\n\n提醒设置：${remindText}`;

      // 如果有描述，添加描述信息
      if (schedule.description) {
        message += `\n\n描述：${schedule.description}`;
      }

      return message;
    },

    clearAiChat() {
      this.$modal
        .confirm("确定要清除所有AI聊天记录吗？", "提示", {
          confirmButtonText: "完全清除",
          cancelButtonText: "取消",
          distinguishCancelAndClose: true,
          type: "warning",
        })
        .then(() => {
          // 完全清除
          this.aiMessages = [];
          this.aiSuggestions = [];
          this.aiInputMessage = "";
          this.$message.success("聊天记录已完全清除");
        })
        .catch((action) => {
          // 用户点击取消或关闭对话框，不做任何操作
          if (action === "cancel") {
            // 用户点击取消，什么都不做
            return;
          }
          // 其他情况（如点击关闭按钮）也不做任何操作
        });
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const aiMessagesContent = this.$refs.aiMessagesContent;
        if (aiMessagesContent) {
          aiMessagesContent.scrollTop = aiMessagesContent.scrollHeight;
        }
      });
    },

    checkScrollPosition() {
      this.$nextTick(() => {
        const aiMessagesContent = this.$refs.aiMessagesContent;
        if (aiMessagesContent) {
          const { scrollTop, scrollHeight, clientHeight } = aiMessagesContent;
          const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10;
          this.showScrollToBottom =
            !isAtBottom &&
            aiMessagesContent.scrollHeight > aiMessagesContent.clientHeight;
        }
      });
    },

    getNotificationPermissionStatus() {
      if (!("Notification" in window)) {
        return "不支持";
      }
      switch (Notification.permission) {
        case "granted":
          return "已授权";
        case "denied":
          return "已拒绝";
        case "default":
          return "未设置";
        default:
          return "未知";
      }
    },

    getActiveSchedulesCount() {
      const now = new Date();
      return this.schedules.filter((schedule) => {
        const startTime = new Date(schedule.startTime);
        const endTime = new Date(schedule.endTime);
        return startTime <= now && endTime > now;
      }).length;
    },

    getPendingSchedulesCount() {
      const now = new Date();
      return this.schedules.filter((schedule) => {
        const startTime = new Date(schedule.startTime);
        return startTime > now;
      }).length;
    },

    getCompletedSchedulesCount() {
      const now = new Date();
      return this.schedules.filter((schedule) => {
        const endTime = new Date(schedule.endTime);
        return endTime <= now;
      }).length;
    },

    showDebugInfo() {
      const debugInfo = {
        totalSchedules: this.schedules.length,
        remindedSchedules: Array.from(this.remindedSchedules),
        currentTime: new Date().toLocaleString(),
        upcomingReminders: [],
        activeSchedules: 0,
        completedSchedules: 0,
        pendingSchedules: 0,
      };

      const now = new Date();

      // 统计日程状态
      this.schedules.forEach((schedule) => {
        const startTime = new Date(schedule.startTime);
        const endTime = new Date(schedule.endTime);

        if (endTime <= now) {
          debugInfo.completedSchedules++;
        } else if (startTime <= now) {
          debugInfo.activeSchedules++;
        } else {
          debugInfo.pendingSchedules++;
        }
      });

      // 计算即将到来的提醒
      this.schedules.forEach((schedule) => {
        const remindType =
          schedule.remind || this.reminderSettings.defaultRemindTime;
        if (remindType && remindType !== "none") {
          const startTime = new Date(schedule.startTime);
          const endTime = new Date(schedule.endTime);

          // 只检查未开始且未结束的日程
          if (startTime > now && endTime > now) {
            const minutesUntilStart = Math.floor(
              (startTime - now) / (1000 * 60)
            );

            // 检查是否需要提醒
            let shouldRemind = false;
            let remindReason = "";

            switch (remindType) {
              case "1min":
                shouldRemind = minutesUntilStart === 1;
                remindReason = "提前1分钟";
                break;
              case "5min":
                shouldRemind =
                  minutesUntilStart === 5 ||
                  (minutesUntilStart >= 1 && minutesUntilStart < 5);
                remindReason =
                  minutesUntilStart === 5
                    ? "提前5分钟"
                    : `距离开始还有${minutesUntilStart}分钟`;
                break;
              case "15min":
                shouldRemind =
                  minutesUntilStart === 15 ||
                  (minutesUntilStart >= 1 && minutesUntilStart < 5);
                remindReason =
                  minutesUntilStart === 15
                    ? "提前15分钟"
                    : `距离开始还有${minutesUntilStart}分钟`;
                break;
              case "30min":
                shouldRemind =
                  minutesUntilStart === 30 ||
                  (minutesUntilStart >= 1 && minutesUntilStart < 5);
                remindReason =
                  minutesUntilStart === 30
                    ? "提前30分钟"
                    : `距离开始还有${minutesUntilStart}分钟`;
                break;
              case "1hour":
                shouldRemind =
                  minutesUntilStart === 60 ||
                  (minutesUntilStart >= 1 && minutesUntilStart < 5);
                remindReason =
                  minutesUntilStart === 60
                    ? "提前1小时"
                    : `距离开始还有${minutesUntilStart}分钟`;
                break;
              case "1day":
                shouldRemind =
                  minutesUntilStart === 1440 ||
                  (minutesUntilStart >= 1 && minutesUntilStart < 5);
                remindReason =
                  minutesUntilStart === 1440
                    ? "提前1天"
                    : `距离开始还有${minutesUntilStart}分钟`;
                break;
            }

            if (shouldRemind) {
              debugInfo.upcomingReminders.push({
                schedule: schedule.title,
                startTime: startTime.toLocaleString(),
                remindReason: remindReason,
                minutesUntilStart: minutesUntilStart,
              });
            }
          }
        }
      });

      this.$alert(JSON.stringify(debugInfo, null, 2), "调试信息", {
        confirmButtonText: "确定",
        customClass: "debug-dialog",
      });
    },

    // 新增：格式化更新时间
    formatUpdateTime(date) {
      const now = new Date();
      const diff = now - date;

      if (diff < 1000) {
        return "刚刚";
      } else if (diff < 60 * 1000) {
        return `${Math.floor(diff / 1000)}秒前`;
      } else if (diff < 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 1000))}分钟前`;
      } else {
        return date.toLocaleTimeString();
      }
    },
    handleDeleteFromDialog() {
      this.$modal
        .confirm("是否确认删除该日程？")
        .then(() => {
          delScheduleBatch([this.scheduleForm.id]).then(() => {
            this.$modal.msgSuccess("删除成功");
            this.dialogVisible = false;
            this.loadSchedules();
            // 清理相关提醒记录
            this.clearReminderRecord(this.scheduleForm.id);
          });
        })
        .catch(() => {});
    },
    startRealtimeUpdateTimer() {
      this.realtimeUpdateTimer = setInterval(() => {
        this.updateRealtimeData();
      }, this.realtimeUpdateInterval);
    },
    updateRealtimeData() {
      // 如果页面不可见，暂停更新以节省资源
      if (!this.isPageVisible) {
        return;
      }

      const startTime = performance.now();
      const now = new Date();
      this.lastUpdateTime = now;

      // 强制更新计算属性
      this.$forceUpdate();

      // 检查是否有新的即将到来的日程需要显示
      this.checkNewUpcomingSchedules();

      // 检查是否有日程状态发生变化
      this.checkScheduleStatusChanges();
    },
    checkNewUpcomingSchedules() {
      const now = new Date();
      const currentUpcoming = this.upcomingSchedules;
      const previousUpcoming = this.upcomingSchedulesCache;

      // 检查是否有新的日程进入即将到来的列表
      const newSchedules = currentUpcoming.filter(
        (current) =>
          !previousUpcoming.some((previous) => previous.id === current.id)
      );

      if (newSchedules.length > 0) {
        newSchedules.forEach((schedule) => {
          console.log(`[实时更新] 新日程进入即将到来列表: ${schedule.title}`);
          // 可以在这里添加新日程进入的提示
          this.$notify({
            title: "新日程提醒",
            message: `"${schedule.title}" 即将开始`,
            type: "info",
            duration: 3000,
            position: "top-right",
          });
        });
      }
    },
    checkScheduleStatusChanges() {
      const now = new Date();
      const currentUpcoming = this.upcomingSchedules;
      const previousUpcoming = this.upcomingSchedulesCache;

      currentUpcoming.forEach((current) => {
        const previous = previousUpcoming.find((p) => p.id === current.id);
        if (previous) {
          // 检查状态变化
          if (previous.isUrgent !== current.isUrgent) {
            if (current.isUrgent) {
              console.log(`[实时更新] 日程开始: ${current.title}`);
              this.$notify({
                title: "日程开始",
                message: `"${current.title}" 现在开始`,
                type: "success",
                duration: 5000,
                position: "top-right",
              });
            }
          }

          // 检查是否即将开始
          if (!previous.isStartingSoon && current.isStartingSoon) {
            console.log(`[实时更新] 日程即将开始: ${current.title}`);
            this.$notify({
              title: "日程即将开始",
              message: `"${current.title}" 将在5分钟内开始`,
              type: "warning",
              duration: 5000,
              position: "top-right",
            });
          }

          // 检查是否即将结束
          if (!previous.isEndingSoon && current.isEndingSoon) {
            console.log(`[实时更新] 日程即将结束: ${current.title}`);
            this.$notify({
              title: "日程即将结束",
              message: `"${current.title}" 将在5分钟内结束`,
              type: "info",
              duration: 5000,
              position: "top-right",
            });
          }
        }
      });
    },
    manualRefresh() {
      this.refreshing = true;
      this.loadSchedules()
        .then(() => {
          this.refreshing = false;
          this.$message.success("数据已刷新");
        })
        .catch(() => {
          this.refreshing = false;
        });
    },
    // 新增：更新刷新间隔
    updateRefreshInterval() {
      // 清除现有定时器
      if (this.realtimeUpdateTimer) {
        clearInterval(this.realtimeUpdateTimer);
      }

      // 重新启动定时器
      this.startRealtimeUpdateTimer();

      this.$message.success(
        `更新频率已调整为 ${this.realtimeUpdateInterval / 1000} 秒`
      );
    },
    setupPageVisibilityListener() {
      // 添加页面可见性监听
      window.addEventListener("visibilitychange", () => {
        this.isPageVisible = !document.hidden;
      });
    },
    onStartTimeChange(value) {
      // 当开始时间改变时，清除结束时间并重新验证
      if (value && this.scheduleForm.endTime) {
        const startTime = new Date(value);
        const endTime = new Date(this.scheduleForm.endTime);

        if (endTime <= startTime) {
          this.scheduleForm.endTime = "";
          this.$message.warning("开始时间已更改，请重新选择结束时间");
        }
      }

      // 重新验证表单
      this.$nextTick(() => {
        this.$refs.scheduleForm.validateField("endTime");
      });
    },
    validateEndTime(rule, value, callback) {
      const startTime = new Date(this.scheduleForm.startTime);
      const endTime = new Date(value);
      if (endTime <= startTime) {
        callback(new Error("结束时间必须大于开始时间"));
      } else {
        callback();
      }
    },
    showAiExamples() {
      const examples = [
        {
          title: "创建日程",
          examples: [
            '帮我创建一个会议，标题为"项目讨论会"，明天下午2点开始',
            '安排一个日程，标题为"客户拜访"，后天上午10点到11点',
            '添加一个任务，标题为"准备报告"，今天下午3点开始',
          ],
        },
        {
          title: "优化日程",
          examples: [
            "帮我优化今天的日程安排",
            "检查时间冲突",
            "建议空闲时间安排",
          ],
        },
      ];

      let message = "AI助手使用示例：\n\n";
      examples.forEach((category) => {
        message += `${category.title}：\n`;
        category.examples.forEach((example) => {
          message += `• ${example}\n`;
        });
        message += "\n";
      });

      message +=
        '提示：AI会根据您的需求自动解析日程信息，并提供"应用AI建议"按钮来快速创建日程。';

      this.$alert(message, "AI助手使用示例", {
        confirmButtonText: "知道了",
        customClass: "ai-examples-dialog",
        dangerouslyUseHTMLString: false,
      });
    },
    checkAiServiceStatus() {
      // 设置状态为检查中
      this.aiServiceStatus = {
        type: 'info',
        text: '检查中',
        icon: 'el-icon-loading',
        message: '正在检查AI服务状态...'
      };

      // 发送一个简单的测试请求来检查AI服务状态
      generateAnswerWithRetry("deepseek-r1:1.5b", "测试", 1)
        .then(() => {
          // AI服务正常
          this.aiServiceStatus = {
            type: 'success',
            text: '服务正常',
            icon: 'el-icon-success',
            message: 'AI服务运行正常，可以正常使用'
          };
        })
        .catch((error) => {
          // AI服务异常
          let statusType = 'warning';
          let statusText = '服务异常';
          let statusIcon = 'el-icon-warning';
          let statusMessage = 'AI服务暂时不可用';

          if (error.message.includes('超时')) {
            statusType = 'danger';
            statusText = '响应超时';
            statusIcon = 'el-icon-time';
            statusMessage = 'AI服务响应超时，请稍后重试';
          } else if (error.message.includes('网络')) {
            statusType = 'danger';
            statusText = '网络异常';
            statusIcon = 'el-icon-connection';
            statusMessage = '网络连接异常，请检查网络';
          }

          this.aiServiceStatus = {
            type: statusType,
            text: statusText,
            icon: statusIcon,
            message: statusMessage
          };
        });
    },
    // 初始化AI服务状态（不发送测试请求）
    initAiServiceStatus() {
      this.aiServiceStatus = {
        type: 'info',
        text: '点击检查',
        icon: 'el-icon-question',
        message: '点击检查AI服务状态'
      };
    },
  },
  watch: {
    listViewType(newVal, oldVal) {
      this.$nextTick(() => {
        this.checkScrollPosition();
      });
    },
  },
  mounted() {
    this.checkScrollPosition();
  },
  updated() {
    this.checkScrollPosition();
  },
};
</script>

<style lang="scss" scoped>
.schedule-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.calendar-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.schedule-list-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;

  .el-table {
    margin-top: 10px;
  }

  .el-card__header {
    .el-radio-group {
      margin-right: 10px;
    }
  }
}

.calendar-day {
  height: 100%;
  padding: 5px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .day-number {
    text-align: right;
    font-size: 12px;
    margin-bottom: 2px;
    color: #606266;
    flex-shrink: 0;
  }

  .schedules {
    flex: 1;
    max-height: 60px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 2px;

    .schedule-item {
      color: white;
      font-size: 12px;
      padding: 2px 4px;
      border-radius: 4px;
      cursor: pointer;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      opacity: 0.9;
      transition: all 0.3s ease;
      min-height: 18px;
      display: flex;
      align-items: center;
      line-height: 1.2;

      &:hover {
        opacity: 1;
        transform: translateY(-1px);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  box-sizing: border-box;
  font-weight: 500;
}

.ai-assistant-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  border-left: 4px solid #409eff;

  .el-card__header {
    background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
    color: white;

    span {
      color: white;
      font-weight: 600;
    }

    .el-tag {
      transition: all 0.3s ease;
      border: 1px solid rgba(255, 255, 255, 0.3);
      
      &:hover {
        transform: scale(1.05);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      }

      &.el-tag--success {
        background: rgba(103, 194, 58, 0.2);
        border-color: rgba(103, 194, 58, 0.5);
        color: #67c23a;
      }

      &.el-tag--warning {
        background: rgba(230, 162, 60, 0.2);
        border-color: rgba(230, 162, 60, 0.5);
        color: #e6a23c;
      }

      &.el-tag--danger {
        background: rgba(245, 108, 108, 0.2);
        border-color: rgba(245, 108, 108, 0.5);
        color: #f56c6c;
      }

      &.el-tag--info {
        background: rgba(144, 147, 153, 0.2);
        border-color: rgba(144, 147, 153, 0.5);
        color: #909399;
      }
    }

    .el-button {
      color: white;

      &:hover {
        color: #f0f9ff;
      }

      // 清除按钮特殊样式
      &:first-child {
        color: #ffd700;

        &:hover {
          color: #ffed4e;
          background: rgba(255, 215, 0, 0.2);
        }

        i {
          margin-right: 4px;
        }
      }
    }
  }
}

.ai-assistant-content {
  padding: 20px;
  background: #fafbfc;
  border-radius: 0 0 8px 8px;
}

.ai-input-area {
  position: relative;
  margin-bottom: 20px;

  .el-textarea {
    .el-textarea__inner {
      border-radius: 12px;
      border: 2px solid #e4e7ed;
      transition: all 0.3s ease;

      &:focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
  }
}

.ai-input-tips {
  position: absolute;
  left: 8px;
  bottom: 8px;
  font-size: 11px;
  color: #909399;
  z-index: 1;

  .tip-text {
    background: rgba(255, 255, 255, 0.9);
    padding: 2px 6px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
  }
}

.ai-send-btn {
  position: absolute;
  right: 8px;
  bottom: 8px;
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.05);
  }

  &.loading-btn {
    background: #e0e0e0 !important;
    border-color: #e0e0e0 !important;
  }
}

.loading-dots {
  display: inline-flex;
  align-items: center;

  .dot {
    animation: dotPulse 1.4s infinite;
    margin: 0 1px;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes dotPulse {
  0%,
  100% {
    opacity: 0.2;
  }
  50% {
    opacity: 1;
  }
}

.ai-messages {
  margin-bottom: 20px;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.ai-messages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;

  span {
    font-weight: 600;
    color: #495057;
    font-size: 13px;
  }

  .el-button {
    color: #dc3545;
    font-size: 12px;

    &:hover {
      color: #c82333;
      background: rgba(220, 53, 69, 0.1);
    }

    i {
      margin-right: 4px;
    }
  }
}

.ai-messages-content {
  max-height: 250px;
  overflow-y: auto;
  padding: 5px;
  position: relative;

  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 2px;

    &:hover {
      background: #a8a8a8;
    }
  }
}

.ai-message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
  animation: fadeInUp 0.3s ease;

  &.user {
    justify-content: flex-end;

    .ai-message-content {
      background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
      color: white;
      border-radius: 12px 4px 12px 12px;
    }
  }

  &.assistant {
    justify-content: flex-start;

    .ai-message-content {
      background: white;
      border: 1px solid #e4e7ed;
      border-radius: 4px 12px 12px 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }

    &.thinking {
      .ai-message-content {
        background: #f8f9fa;
        border-color: #e6a23c;
        border-left: 3px solid #e6a23c;
      }
    }

    &.error {
      .ai-message-content {
        background: #fef0f0;
        border-color: #f56c6c;
        border-left: 3px solid #f56c6c;
        color: #f56c6c;

        pre {
          color: #f56c6c;
        }
      }
    }
  }

  .ai-avatar {
    margin: 0 10px;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .user-avatar {
      width: 100%;
      height: 100%;
      background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      i {
        font-size: 16px;
        color: white;
      }
    }
  }

  .ai-message-content {
    max-width: 70%;
    padding: 12px 16px;
    font-size: 14px;
    line-height: 1.6;
    word-wrap: break-word;

    pre {
      margin: 0;
      white-space: pre-wrap;
      font-family: inherit;
    }
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.ai-suggestions {
  margin-top: 15px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;

  h4 {
    margin: 0 0 10px 0;
    color: #303133;
    font-size: 13px;
    font-weight: 600;
  }
}

.suggestion-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.suggestion-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 6px;
  font-size: 12px;
  padding: 4px 8px;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  &.el-tag--primary {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    border-color: #409eff;
    color: white;

    &:hover {
      background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
    }
  }

  &.el-tag--success {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    border-color: #67c23a;
    color: white;

    &:hover {
      background: linear-gradient(135deg, #85ce61 0%, #67c23a 100%);
    }
  }

  &.el-tag--warning {
    background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
    border-color: #e6a23c;
    color: white;

    &:hover {
      background: linear-gradient(135deg, #ebb563 0%, #e6a23c 100%);
    }
  }
}

.countdown-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  border-left: 4px solid #e6a23c;

  .el-card__header {
    background: linear-gradient(135deg, #e6a23c 0%, #f56c6c 100%);
    color: white;

    span {
      color: white;
      font-weight: 600;
    }

    .update-time {
      font-size: 12px;
      color: rgba(255, 255, 255, 0.8);
      margin-left: 10px;
    }

    .el-tag {
      background: rgba(103, 194, 58, 0.2);
      border-color: rgba(103, 194, 58, 0.3);
      color: #67c23a;

      i {
        animation: spin 2s linear infinite;
        margin-right: 4px;
      }
    }

    .el-select {
      .el-input__inner {
        background: rgba(255, 255, 255, 0.9);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: #303133;
        font-size: 12px;

        &:focus {
          border-color: #409eff;
        }
      }

      .el-input__suffix {
        color: #303133;
      }
    }

    .el-button {
      &:hover {
        background: rgba(255, 255, 255, 0.2);
        border-radius: 4px;
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.countdown-list {
  padding: 20px;
  background: #fafbfc;
  border-radius: 0 0 8px 8px;
}

.countdown-item {
  margin-bottom: 15px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: all 0.3s ease;
  animation: slideInRight 0.3s ease;

  &:hover {
    transform: translateX(5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &.urgent {
    border-left: 4px solid #f56c6c;
    background: linear-gradient(135deg, #fff5f5 0%, #fff 100%);

    .remaining-value {
      color: #f56c6c;
      font-weight: 600;
      animation: pulse 2s infinite;
    }
  }

  &.starting-soon {
    border-left: 4px solid #e6a23c;
    background: linear-gradient(135deg, #fffbf0 0%, #fff 100%);

    .remaining-value {
      color: #e6a23c;
      font-weight: 600;
      animation: pulse 1.5s infinite;
    }
  }

  &.ending-soon {
    border-left: 4px solid #909399;
    background: linear-gradient(135deg, #f8f9fa 0%, #fff 100%);

    .remaining-value {
      color: #909399;
      font-weight: 600;
      animation: pulse 2.5s infinite;
    }
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

.countdown-info {
  flex: 1;
  margin-right: 15px;
}

.schedule-title {
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
  font-size: 14px;
}

.countdown-time,
.countdown-remaining {
  font-size: 12px;
  color: #606266;
  margin-bottom: 4px;
  display: flex;
  align-items: center;

  .time-label,
  .remaining-label {
    min-width: 70px;
    color: #909399;
  }

  .time-value {
    color: #303133;
    font-weight: 500;
  }

  .remaining-value {
    color: #409eff;
    font-weight: 600;

    &.urgent-text {
      color: #f56c6c;
    }

    &.starting-soon-text {
      color: #e6a23c;
    }

    &.ending-soon-text {
      color: #909399;
    }
  }
}

.countdown-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;

  .el-button {
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.05);
    }
  }
}

.schedule-status {
  margin-top: 8px;

  .el-tag {
    border-radius: 4px;

    i {
      margin-right: 4px;
    }
  }
}

@media (max-width: 768px) {
  .schedule-container {
    padding: 10px;
  }

  .ai-message {
    .ai-message-content {
      max-width: 85%;
    }
  }

  .countdown-item {
    flex-direction: column;
    align-items: flex-start;

    .countdown-actions {
      margin-top: 10px;
      width: 100%;
      justify-content: flex-end;
    }
  }

  .suggestion-list {
    justify-content: center;
  }
}

.ai-messages::-webkit-scrollbar,
.countdown-list::-webkit-scrollbar {
  width: 6px;
}

.ai-messages::-webkit-scrollbar-track,
.countdown-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.ai-messages::-webkit-scrollbar-thumb,
.countdown-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;

  &:hover {
    background: #a8a8a8;
  }
}

.el-notification {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-table {
  .el-table__header-wrapper {
    th {
      background: #fafbfc;
      color: #303133;
      font-weight: 600;
    }
  }

  .el-table__body-wrapper {
    tr:hover {
      background: #f5f7fa;
    }
  }
}

.el-calendar {
  .el-calendar__header {
    padding: 20px;
    background: #fafbfc;
    border-radius: 8px 8px 0 0;
  }

  .el-calendar__body {
    .el-calendar-table {
      .el-calendar-day {
        height: 80px;
        padding: 8px;

        &:hover {
          background: #f5f7fa;
        }
      }
    }
  }
}

.reminder-settings {
  padding: 20px;

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
}

.reminder-preview {
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;

  h4 {
    margin: 0 0 10px 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
  }

  .preview-message {
    padding: 10px;
    background: white;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
    font-size: 14px;
    color: #606266;
  }
}

.optimize-content {
  padding: 20px;
}

.optimize-analysis {
  margin-bottom: 30px;

  h4 {
    margin: 0 0 15px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
}

.analysis-items {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.analysis-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e4e7ed;

  .analysis-text {
    font-size: 14px;
    color: #606266;
  }
}

.optimize-suggestions {
  h4 {
    margin: 0 0 15px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
}

.suggestion-card {
  margin-bottom: 15px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  .el-card__body {
    padding: 15px;
  }
}

.suggestion-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;

  i {
    font-size: 16px;
    color: #409eff;
  }

  .suggestion-title {
    flex: 1;
    font-weight: 600;
    color: #303133;
    font-size: 14px;
  }
}

.suggestion-content {
  margin-bottom: 15px;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.suggestion-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.ai-empty-state {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;

  .empty-icon {
    font-size: 48px;
    color: #409eff;
    margin-bottom: 10px;
  }

  .empty-text {
    h4 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }

    p {
      margin: 5px 0 0 0;
      font-size: 14px;
      color: #606266;
    }
  }
}

.scroll-to-bottom-btn {
  position: absolute;
  right: 10px;
  bottom: 10px;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  background: rgba(64, 158, 255, 0.9);
  color: white;
  border: none;
  outline: none;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  z-index: 10;

  &:hover {
    background: rgba(103, 194, 58, 0.9);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
  }

  i {
    font-size: 14px;
  }
}

// 提醒弹框样式
:global(.schedule-reminder-notification) {
  border-left: 4px solid #e6a23c;
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);

  .el-notification__title {
    color: #e6a23c;
    font-weight: 600;
  }

  .el-notification__content {
    white-space: pre-line;
    line-height: 1.6;
  }
}

:global(.schedule-reminder-dialog) {
  .el-message-box__header {
    background: linear-gradient(135deg, #e6a23c 0%, #f56c6c 100%);
    color: white;

    .el-message-box__title {
      color: white;
      font-weight: 600;
    }

    .el-message-box__headerbtn {
      .el-message-box__close {
        color: white;

        &:hover {
          color: #f0f9ff;
        }
      }
    }
  }

  .el-message-box__content {
    padding: 20px;
    white-space: pre-line;
    line-height: 1.6;
    font-size: 14px;
  }

  .el-message-box__btns {
    .el-button--primary {
      background: #e6a23c;
      border-color: #e6a23c;

      &:hover {
        background: #d49426;
        border-color: #d49426;
      }
    }
  }
}

.reminder-debug {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;

  h4 {
    margin: 0 0 10px 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
  }

  .debug-info {
    p {
      margin: 5px 0;
      color: #606266;
      font-size: 12px;
    }
  }
}

.debug-dialog {
  .el-message-box__content {
    padding: 20px;
    white-space: pre-line;
    line-height: 1.6;
    font-size: 14px;
  }

  .el-message-box__btns {
    .el-button--primary {
      background: #e6a23c;
      border-color: #e6a23c;

      &:hover {
        background: #d49426;
        border-color: #d49426;
      }
    }
  }
}

:global(.reminder-info-dialog) {
  .el-message-box__content {
    padding: 20px;
    white-space: pre-line;
    line-height: 1.6;
    font-size: 14px;
  }

  .el-message-box__btns {
    .el-button--primary {
      background: #e6a23c;
      border-color: #e6a23c;

      &:hover {
        background: #d49426;
        border-color: #d49426;
      }
    }
  }
}

:global(.ai-examples-dialog) {
  .el-message-box__content {
    padding: 20px;
    white-space: pre-line;
    line-height: 1.6;
    font-size: 14px;
    max-height: 400px;
    overflow-y: auto;
  }

  .el-message-box__btns {
    .el-button--primary {
      background: #409eff;
      border-color: #409eff;

      &:hover {
        background: #66b1ff;
        border-color: #66b1ff;
      }
    }
  }
}

.thinking-content {
  color: #909399;
  font-style: italic;
}

.thinking-dots {
  display: inline-flex;
  align-items: center;

  .dot {
    animation: dotPulse 1.4s infinite;
    margin: 0 1px;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes dotPulse {
  0%,
  100% {
    opacity: 0.2;
  }
  50% {
    opacity: 1;
  }
}

.thinking-text {
  margin-right: 5px;
}
</style>